package net.towee.model.account.impl;

import java.util.ArrayList;
import java.util.List;

import net.towee.model.account.AccountIdentity;
import net.towee.server.persistence.impl.MongoDbStore;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Indexed;
import com.google.code.morphia.annotations.PostLoad;
import com.google.gwt.regexp.shared.RegExp;

/**
 * Implementation of account identity
 * @author c58
 */
@Entity(MongoDbStore.ACCOUNT_IDENTITY_COLLECTION)
public class AccountIdentityImpl implements AccountIdentity {
	// This is id of user in account collection
	@Id private String id;
	
	private String firstName;
	private String lastName;
	
	@Indexed 
	private String nickName;
	private boolean online;
	
	// Needed for fast searching users by group 
	@Indexed transient public List<String> groups;

	public AccountIdentityImpl() {}
	public AccountIdentityImpl(String id) {
		this.id = id;
		this.online = true;
	}
	
	@PostLoad
	private void createEmptyFields() {
		if(groups == null)
			groups = new ArrayList<String>();
	}
	
	@Override
	public String getId() {
		return id;
	}

	@Override
	public boolean isOnline() {
		return online;
	}

	@Override
	public String getFirstName() {
		return firstName;
	}

	@Override
	public String getLastName() {
		return lastName;
	}

	@Override
	public String getFullName() {
		if(firstName == null && lastName == null)
			if(nickName == null)
				return "anonymous";
			else
				return nickName;
		
		return firstName+" "+lastName;
	}

	@Override
	public String getNickName() {
		return nickName;
	}

	@Override
	public void setFirstName(String name) {
		this.firstName = name.trim();
	}

	@Override
	public void setLastName(String name) {
		this.lastName = name.trim();
	}

	@Override
	public void setFullName(String name) {
		int pos;
		
		if( (pos=name.indexOf(" ")) >0) {
			this.firstName = name.substring(0,pos).trim();
			this.lastName = name.substring(pos+1).trim();
		}	else {
			this.firstName = name;
		}
	}

	@Override
	public boolean setNickName(String name) {
		if( name == null ) {
			this.nickName = null;
			return true;
		}
		
		if( !RegExp.compile(NICKNAME_VLIDATION_PATTERN, "i").test(name) )
			return false;
			
		this.nickName = name.trim().toLowerCase();
		return true;
	}
	
	@Override
	public void setOnlineState(boolean state) {
		this.online = state;
	}

	@Override
	public String toString() {
		return "AccountIdentity('"+nickName+"', '"+firstName+"', '"+lastName+"');";
	}
	
	@Override
	public boolean equals(Object o) {
		if(o == this)
			return true;
		if(o instanceof AccountIdentity && ((AccountIdentity)o).getId().equals(getId()))
			return true;
		
		return false;
	}
	@Override
	public String getPhotoId() {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void setPhotoId(String id) {
		// TODO Auto-generated method stub
		
	}
}
